package cn.ug.member.service.impl;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.ensure.Ensure;
import cn.ug.enums.CouponTriggerEnum;
import cn.ug.enums.ProductTypeEnum;
import cn.ug.feign.CouponRepertoryService;
import cn.ug.feign.ProductService;
import cn.ug.member.bean.response.MemberUserFindBean;
import cn.ug.member.mapper.ChannelShareMemberMapper;
import cn.ug.member.mapper.MemberOperationRecordMapper;
import cn.ug.member.mapper.MemberUserMapper;
import cn.ug.member.mapper.entity.ChannelShareMember;
import cn.ug.member.mapper.entity.MemberOperationRecord;
import cn.ug.member.mapper.entity.MemberUser;
import cn.ug.member.service.MemberOperationService;
import cn.ug.product.bean.response.ProductFindBean;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员操作记录
 *
 * @Author zhangweijie
 * @Date 2019/4/26 0026
 * @time 上午 10:17
 **/
@Service
public class MemberOperationServiceImpl implements MemberOperationService {

    @Autowired
    private MemberOperationRecordMapper memberOperationRecordMapper;

    @Autowired
    private MemberUserMapper memberUserMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private CouponRepertoryService couponRepertoryService;

    @Autowired
    private ChannelShareMemberMapper channelShareMemberMapper;

    private static final String NEW_WORK_ONLINE_TIME = "2019-05-14";

    private static Logger logger = LoggerFactory.getLogger(MemberOperationServiceImpl.class);

    @Override
    public boolean addClick(String memberId, Integer type) {
        MemberOperationRecord memberOperationRecord = memberOperationRecordMapper.selectBymemberId(memberId);
        if (memberOperationRecord == null) {
            //新增记录
            memberOperationRecord = new MemberOperationRecord();
            memberOperationRecord.setMemberId(memberId);
            switch (type) {
                case 1:
                    memberOperationRecord.setLoginNum(1);
                    break;
                case 2:
                    memberOperationRecord.setGuideNum(1);
                    break;
                case 3:
                    memberOperationRecord.setBuyGoldNum(1);
                    break;
                case 4:
                    memberOperationRecord.setLeaseBackNum(1);
                    break;
                case 5:
                    memberOperationRecord.setCouponNum(1);
                    break;
                case 6:
                    memberOperationRecord.setLearnMoreNum(1);
                    break;
                case 7:
                    memberOperationRecord.setSkipNum(1);
                    break;
            }
            int rows = memberOperationRecordMapper.insertSelective(memberOperationRecord);
            Ensure.that(rows).isLt(1, "00000005");
            return true;
        }

        //修改 1.登陆次数  2.引导页  3.买金点击数  4.回租点击数 5.查看优惠卷点击数 6.了解更多点击数 7.跳过点击数
        switch (type) {
            case 1:
                memberOperationRecord.setLoginNum(memberOperationRecord.getLoginNum() + 1);
                break;
            case 2:
                memberOperationRecord.setGuideNum(memberOperationRecord.getGuideNum() + 1);
                break;
            case 3:
                memberOperationRecord.setBuyGoldNum(memberOperationRecord.getBuyGoldNum() + 1);
                break;
            case 4:
                memberOperationRecord.setLeaseBackNum(memberOperationRecord.getLeaseBackNum() + 1);
                break;
            case 5:
                memberOperationRecord.setCouponNum(memberOperationRecord.getCouponNum() + 1);
                break;
            case 6:
                memberOperationRecord.setLearnMoreNum(memberOperationRecord.getLearnMoreNum() + 1);
                break;
            case 7:
                memberOperationRecord.setSkipNum(memberOperationRecord.getSkipNum() + 1);
                break;
        }
        int rows = memberOperationRecordMapper.updateByPrimaryKeySelective(memberOperationRecord);
        Ensure.that(rows).isLt(1, "00000005");
        return true;
    }


    @Override
    public Map findLoginNum(String memberId) {
        Map resultMap = new HashMap();
        resultMap.put("popup", 1);
        MemberOperationRecord memberOperationRecord = memberOperationRecordMapper.selectBymemberId(memberId);
        if (memberOperationRecord == null) {
            resultMap.put("loginNum", 1);
        } else {
            resultMap.put("loginNum", memberOperationRecord.getLoginNum());
        }
        MemberUserFindBean memberUserFindBean = memberUserMapper.queryMemberUserById(memberId);
        //用户注册时间在新业务上线时间之前  不弹新人大礼包框
        if (NEW_WORK_ONLINE_TIME.compareTo(memberUserFindBean.getAddTimeString().substring(0, 10)) > 0) {
            resultMap.put("popup", 0);
        }
        //非首次登陆 不弹新人大礼包框
        if (memberOperationRecord.getLoginNum() > 1) {
            resultMap.put("popup", 0);
        }
        return resultMap;
    }

    @Override
    public int findTbillPopup(String memberId, String orderNo) {
        MemberOperationRecord memberOperationRecord = memberOperationRecordMapper.selectBymemberId(memberId);
        if (memberOperationRecord == null) {
            //新增记录
            memberOperationRecord = new MemberOperationRecord();
            memberOperationRecord.setMemberId(memberId);
            int rows = memberOperationRecordMapper.insertSelective(memberOperationRecord);
            Ensure.that(rows).isLt(1, "00000005");
            memberOperationRecord = memberOperationRecordMapper.selectBymemberId(memberId);
        }
        Map resultMap = memberUserMapper.queryProductById(orderNo);
        if (resultMap != null && StringUtils.isNotBlank(resultMap.get("productId").toString())) {
            SerializeObject<ProductFindBean> serializeObject = productService.queryProductById(resultMap.get("productId").toString());
            if (serializeObject != null && serializeObject.getData() != null) {
                ProductFindBean productFindBean = serializeObject.getData();
                if ("2".equalsIgnoreCase(resultMap.get("status").toString())) {
                    //用户首次购买成功进入待处理提单  -适用于实物金产品
                    if ("买金".equalsIgnoreCase(resultMap.get("source").toString()) &&
                            ProductTypeEnum.ENTITY.getType() == productFindBean.getType()) {
                        if (memberOperationRecord.getBuyGoldPendingStatus() > 0) {
                            return 0;
                        }
                        memberOperationRecord.setBuyGoldPendingStatus(1);
                        memberOperationRecordMapper.updateByPrimaryKeySelective(memberOperationRecord);
                        return 1;
                    } else if (ProductTypeEnum.ENTITY.getType() == productFindBean.getType() ||
                            ProductTypeEnum.DISCOUNT_GOLD.getType() == productFindBean.getType()) {
                        //用户首笔回租到期进入待处理提单  -实物金和折扣金产品
                        if (memberOperationRecord.getBuyGoldLeasebackStatus() > 0) {
                            return 0;
                        }
                        memberOperationRecord.setBuyGoldLeasebackStatus(1);
                        memberOperationRecordMapper.updateByPrimaryKeySelective(memberOperationRecord);
                        return 1;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 点赞成功发送黄金红包
     *
     * @param channelId
     * @param memberId
     * @param friendId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SerializeObject giveLike(String channelId, String memberId, String friendId) {
        if (StringUtils.isBlank(memberId) || StringUtils.isBlank(friendId)) {
            return new SerializeObject<>(ResultType.ERROR, "00000002");
        }
        MemberUser member = memberUserMapper.findById(memberId);
        if (null == member) {
            return new SerializeObject<>(ResultType.ERROR, "14000270");
        }
        MemberUser friend = memberUserMapper.findById(friendId);
        if (null == friend) {
            return new SerializeObject<>(ResultType.ERROR, "14000271");
        }
        Map map = new HashMap();
        map.put("channelId",channelId);
        map.put("memberId",memberId);
        map.put("friendId",friendId);
        List<ChannelShareMember> list = channelShareMemberMapper.findJoinMember(map);
        if (list != null && list.size() > 0) {
            return new SerializeObject<>(ResultType.EXCEPTION, "14000273");
        }

        SerializeObject memberBean = couponRepertoryService.giveCoupons(memberId, CouponTriggerEnum.GIVELIKE.getTrigger(), member.getMobile());
        SerializeObject friendBean = couponRepertoryService.giveCoupons(friendId, CouponTriggerEnum.GIVELIKE.getTrigger(), friend.getMobile());
        if (memberBean != null) {
            logger.info("点赞成功分享人赠送黄金红包结果：" + "【" +memberBean.getCode() + "】" + memberBean.getMsg());
        }
        if (friendBean != null) {
            logger.info("点赞成功被分享人赠送黄金红包结果：" + "【" +memberBean.getCode() + "】" + friendBean.getMsg());
        }
        if (ResultType.NORMAL == memberBean.getCode() && ResultType.NORMAL == friendBean.getCode()) {
            //保存分享记录
            ChannelShareMember channelShareMember = new ChannelShareMember();
            channelShareMember.setChannelId(channelId);
            channelShareMember.setMemberId(memberId);
            channelShareMember.setFriendId(friendId);
            channelShareMember.setAddTime(LocalDateTime.now());
            channelShareMember.setModifyTime(LocalDateTime.now());
            int rows = channelShareMemberMapper.insert(channelShareMember);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObject<>(ResultType.ERROR, "00000005");
    }
}
